import random,time,requests,json
from model.models import db
from flask import Blueprint, jsonify, send_file, request, redirect
from flask_restful import Api, Resource,reqparse
from captcha.image import ImageCaptcha
from utils.myredis import r
from utils.sms import send_message
from utils.myjwt import myjwt
from model.models import *

user_dp = Blueprint('user_dp', __name__)

api = Api(user_dp)

class ImgCode(Resource):
    def get(self,uuid):
        if not uuid:
            return jsonify({"code":400,"msg":"没有参数"})
        #生成图片验证码
        code = random.randint(1000,9999)
        img = ImageCaptcha()
        img_byte = img.generate(str(code))
        #存到redis
        key = "code_%s" % uuid
        r.str_add(key,code)
        return send_file(img_byte,"png")



api.add_resource(ImgCode,"/imgcode/<uuid>")


class SmsCode(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument("mobile")
        req.add_argument("imagecode")
        req.add_argument("uuid")
        args = req.parse_args()
        mobile = args["mobile"]
        imagecode = args["imagecode"]
        uuid = args["uuid"]
        if not mobile:
            return jsonify({"code":400,"msg":"参数没有"})
        key = "code_%s" % uuid
        code = r.str_get(key)
        if not code:
            return jsonify({"code":400,"msg":"图片验证码以过期"})
        print(code,imagecode)
        if code != imagecode:
            return jsonify({"code":400,"msg":"图片验证码错误"})

        code = random.randint(1000,9999)
        send_message(mobile,code)
        key = "sms_%s" % mobile
        r.str_add(key,code,60)
        return jsonify({"code":200,"msg":"获取成功"})

api.add_resource(SmsCode,"/sendsms")


class Login(Resource):
    def post(self):
        data = reqparse.RequestParser()
        data.add_argument("mobile")
        data.add_argument("code")
        args = data.parse_args()
        mobile = args["mobile"]
        code = args["code"]
        if not all([mobile,code]):
            return jsonify({"code":400,"msg":"参数没有"})
        #校验验证码
        key = "sms_%s" % mobile
        recode = r.str_get(key)
        print(">>",recode)
        if not recode:
            return jsonify({"code":400,"msg":"验证码过期"})
        if code != recode:
            return jsonify({"code":400,"msg":"验证码错误"})
        user_info = User.query.filter(User.mobile == mobile).first()
        if user_info:
            #用户存在直接登录
            data = {"data":{"userid":user_info.id,"mobile":user_info.mobile,"exptime":int(time.time())}}
            token = myjwt.jwt_encode(data)
            return jsonify({"code":200,"msg":"登录成功","token":token,"userid":user_info.id})
        if not user_info:
            #没有用户进行注册
            user = User(mobile=mobile)
            # nikename =
            db.session.add(user)
            db.session.commit()
            data = {"data":{"userid":user_info.id,"mobile":user_info.mobile,"exptime":int(time.time())}}
            token = myjwt.jwt_encode(data)
            return jsonify({"code":200,"msg":"注册成功并登录","token":token,"userid":user_info.id})

api.add_resource(Login,"/login")


# # 微博登录
# class WeiBoUserHeadler(Resource):
#     def get(self):
#         client_id = "3674019597"
#         redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
#         url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
#         client_id, redirect_uri)
#         return jsonify({"code": 200, "url": url})
# api.add_resource(WeiBoUserHeadler,"/getWBurl")
#
#
# class WeiBoHeadler(Resource):
#     def get(self):
#         code = request.args.get("code")
#         # print('aaaaaaaaaa',code)
#         # 向access_token接口发送post请求
#         data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
#                 "grant_type": "authorization_code",
#                 'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
#         res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
#         # 根据返回结果操作
#         # 获取token和uid
#         message = json.loads(res.text)
#
#         token = message['access_token']
#         uid = message['uid']
#         # print("wwwwwwwwww",token,uid)
#         # 查询数据库中是否存在，如果存在用用户信息生成jwt token返回
#         # sql = "select user.id,user.mobile from sf_login inner join user on sf_login.userid=user.id where sf_login.uid='%s'" % (
#         #     str(uid))
#         sql = "select user.id from user inner join sf_login on user.id=sf_login.userid where sf_login.uid='%s'"% uid
#         user = db.session.execute(sql)
#         # print("qqqqq",user )
#         # orm查询
#         # 判断是否查询到
#         if user:
#             for i in user:
#                 data = {'data':{'userid':i[0],'exp':int(time.time())}}
#                 token = myjwt.jwt_encode(data)
#                 return redirect("http://localhost:8080/#/UpdateToken?userid="+i[0]+"&token="+token)
#         # 不存在跳转到vue绑定页面 token uid 传递过去
#         return redirect("http://localhost:8080/#/BingMobile?uid="+uid +"&token="+token)
#
# api.add_resource(WeiBoHeadler,"/user/weiboCallback/")

@user_dp.route("/getWburl")
def getWburl():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (client_id, redirect_uri)
    return jsonify({"code": 200, "url": url})

# 微博回调接口
@user_dp.route("/weiboCallback/")
def weiboCallback():
    # 获取code
    code=request.args.get("code")
    # 向access_token接口发送post请求
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    # 根据返回结果操作
    # 获取token和uid
    message=json.loads(res.text)
    print(message)
    token=message["access_token"]
    print(token)
    uid=message["uid"]
    # 查询数据库中是否存在，如果存在用用户信息生成jwt token返回
    # sf=SfLogin.query.filter(SfLogin.uid==uid).first()
    # if sf:
    #     for i in sf:
    #         user=User.query.filter(User.id==sf.userid).first()
    #         data={"data":{"userid":i[0],"exp":int(time.time())}}
    #         token=myjwt.jwt_encode(data)
    #         return redirect("http://localhost:8080/#/updateToken?token=" + token + "&userid=" + str(i[0]))
    sql="select user.id,user.mobile from sf_login inner join user on sf_login.userid=user.id where sf_login.uid='%s'"%(str(uid))
    user=db.session.execute(sql)
    if user:
        # 生成jwt 返回jwt token
        for i in user:
            data={"data":{"userid":i[0],"exp":int(time.time())}}
            token =myjwt.jwt_encode(data)
            return redirect("http://localhost:8080/#/updateToken?token="+str(token)+"&userid="+str(i[0]))
    # 绑定
    return redirect("http://localhost:8080/#/bingMobile?token="+str(token)+"&uid="+str(uid))
# class WeiBoHeadler1(Resource):
@user_dp.route("/bindM",methods=["POST"])
def bindM():
    # 接收参数
    data = json.loads(request.data)
    mobile = data["mobile"]
    uid = data["uid"]
    token = data["token"]
    # 加入用户表
    user = User.query.filter(User.mobile == mobile).first()
    if not user:
        # 添加
        u = User(mobile=mobile, nikename=mobile)
        db.session.add(u)
        db.session.commit()
        # 获取用户信息
        user = User.query.filter(User.mobile == mobile).first()
    sfuser = SfLogin(userid=user.id, webfrom="wb", uid=uid, token=token)
    print("sss", sfuser)
    db.session.add(sfuser)
    db.session.commit()
    data = {"data": user.id, "exp": int(time.time())}
    token = myjwt.jwt_encode(data)
    return redirect("http://localhost:8080/#/updateToken?token=" + token + "&userid=" + str(user.id))






# 购买vip生成订单
# @user_dp.route("/buy",methods=['POST'])
# def buy():
#     # 获取参数
#     data = json.loads(request.data)
#     userid = data['userid']
#     year = data['year']
#     # print("qqqqqqqqq",year)
#     money = 200
#     # 生成订单
#     tmoney = money * int(year)
#     order_on = str(int(time.time())) + str(userid) + str(random.randint(100,999))
#     vip = VipRecord(order_on=order_on,userid=userid,year=year,money=tmoney,active_money=tmoney,status=1)
#     db.session.add(vip)
#     db.session.commit()
#     #支付 返回支付链接
#     alipay = get_ali_object()
#     # 生成支付的url
#     query_params = alipay.direct_pay(
#         subject="test",  # 商品简单描述
#         out_trade_no=str(order_on),  # 用户购买的商品订单号（每次不一样） 20180301073422891
#         total_amount=100,  # 交易金额(单位: 元 保留俩位小数)
#     )
#     pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
#     return jsonify({'code':200,'url':pay_url})
#
#
from utils.comm import get_ali_object
# @user_dp.route("/testalipay")
# def testalipay():
#     orderno = "234864654"
#     alipay = get_ali_object()
#     # 生成支付的url
#     query_params = alipay.direct_pay(
#     subject="test",  # 商品简单描述
#     out_trade_no=str(orderno),  # 用户购买的商品订单号（每次不一样） 20180301073422891
#     total_amount=100,  # 交易金额(单位: 元 保留俩位小数)
#     )
#     pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
#     return redirect(pay_url)
#
#
#




#
#
@user_dp.route('/setVip',methods=['POST'])
def setVip():
    data = json.loads(request.data)
    userid = data['userid']
    year = data['year']
    money = 200
    order_no = str(int(time.time()))+str(userid)+str(random.randint(100,999))
    tmoney = int(money) *int(year)
    vip = VipRecord(userid=userid,year=year,money=tmoney,active_money=tmoney,status=1,order_on=order_no)
    db.session.add(vip)
    db.session.commit()
    alipay = get_ali_object()
    query_params = alipay.direct_pay(
        subject=str(userid),  # 商品简单描述
        out_trade_no=order_no,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(tmoney),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({'code': 200, 'url': pay_url})
import datetime
@user_dp.route('/callback')
def call():
    order_no = request.args.get('out_trade_no')
    print('lllll',order_no)
    res = VipRecord.query.filter_by(order_on=order_no).first()
    print(res)
    uid = int(res.userid)
    year=res.year
    if int(year)==1:
        year=365
    elif int(year)==2:
        year = 365*2
    elif int(year)==3:
        year = 365*3
    # try:
    stime = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
    etime = datetime.datetime.now() +datetime.timedelta(days=year)
    etime = datetime.datetime.strftime(etime,"%Y-%m-%d %H:%M:%S")
    vip = Vip(userid=uid,s_time=stime,e_time=etime)
    db.session.add(vip)

    order=VipRecord.query.filter_by(order_on=order_no).first()
    order.status = 2
    user = User.query.filter_by(id=uid).first()
    user.level = 2
    # User.query.filter_by(userid=uid).update(level=2)
    db.session.commit()
    # except:
    #     db.session.rollback()
    return redirect("http://localhost:8080/#/")